package cn.e2win.biz.security;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.e2win.biz.dbo.*;
import org.hsqldb.lib.MD5;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import cn.e2win.base.entity.SysCompany;
import cn.e2win.base.entity.SysUser;
import cn.e2win.biz.user.UserDao;
import cn.e2win.biz.util.PropertiesUtil;
import cn.e2win.biz.util.StringUtils;



public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	public static final String VALIDATE_CODE = "validateCode";
	public static final String USERNAME = "account";
	public static final String PASSWORD = "password";
	
	public static final String LOGINTYPE = "loginType";
	public static final String LOGINTYPE_MOBILE = "mobile";
	public static final String LOGINTYPE_WEB = "web";
	
	public static String SUPER_ADMIN_TELNO = null;
	
	private UserDao userDao;
	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		
		/*if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}*/
		
		//init super administractor telno
		if (SUPER_ADMIN_TELNO == null) {
			SUPER_ADMIN_TELNO = PropertiesUtil.getProperty(PropertiesUtil.ADMIN_TEL_NO);
		}
		
		//登录类型放入session
		String loginType =  request.getParameter(LOGINTYPE);
		request.getSession().setAttribute(LOGINTYPE, loginType);
		
		//checkValidateCode(request);
		
		String username = obtainUsername(request);
		String password = obtainPassword(request);
		//验证用户账号与密码是否对应
		username = username.trim();
		
		SysUser user = null;
		
		//判断是否是超级管理员--配置文件中配置的
		String errMsg = "登录失败，帐号或密码错误!";
		
		/*List<SysUser> users = this.userDao.findBy(USERNAME, username);
		if(users.size()<1){
			request.getSession().setAttribute("errMsg",errMsg);
			throw new AuthenticationServiceException(errMsg);
		}
		user = users.get(0);
		if(user == null || !user.getPassword().equals(password)) {
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg); 
		}*/
		
		List<SysUser> list= userDao.getUserByAccount(username);
		if(list==null || list.size()!=1){
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg);
		}else{
			user = list.get(0);
		}

		if(user!=null && !user.getPassword().equals(password)) {
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg);
		}
		if(user.getActiveStatusInt()!=1) {
			errMsg = "该帐号已被停用！";
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg); 
		}
		SysCompany company = (SysCompany)this.userDao.getEntity(SysCompany.class, user.getCoId());
		if(company.getActiveStatusInt()!=1){
			errMsg = "公司帐号已被停用！";
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg); 
		}
		if(company.getExpireDate()==null || company.getExpireDate().before(new Date())){
			errMsg = "公司服务合同已到期，续费后方可启用！";
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg); 
		}

		/**
		 * 验证emp状态
		 */
		String userType = user.getUserType();
		BaseEmp sysEmp = null;
		if(userType.equals("DsEmp")){
			sysEmp = (BaseEmp) userDao.getEntity(DsEmp.class,user.getEmpId());
		}else if(userType.equals("CyzjEmp")){
			sysEmp = (BaseEmp) userDao.getEntity(CyzjEmp.class,user.getEmpId());
			CyzjOrg cyzjOrg = (CyzjOrg) userDao.getEntity(CyzjOrg.class,sysEmp.getOrgId());
			if(!cyzjOrg.getActiveStatusInt().equals(1) || !cyzjOrg.getApproveStatus().equals("APPROVED")){
				errMsg = "创业之家未通过审核！";
				request.getSession().setAttribute("errMsg", errMsg);
				throw new AuthenticationServiceException(errMsg);
			}
		}else if(userType.equals("ZdzxEmp")){
			sysEmp = (BaseEmp) userDao.getEntity(ZdzxEmp.class,user.getEmpId());
		}
		if(sysEmp.getActiveStatusInt().equals("0") || !sysEmp.getApproveStatus().equals("APPROVED")){
			errMsg = "该账号已被停用或未通过审核！";
			request.getSession().setAttribute("errMsg", errMsg);
			throw new AuthenticationServiceException(errMsg);
		}

		
		System.err.println("登录成功!====================login successful");
/*		if(UserSession.isOnLine(user.getId())) {
			request.getSession().setAttribute("errMsg", "当前用户已登录!");
			throw new AuthenticationServiceException("当前用户已登录!"); 
		}*/
		
		user.setLoginFrom(request.getParameter("loginFrom"));
		
		UserSession.addUser(user);
		

		//UsernamePasswordAuthenticationToken实现 Authentication
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		// Place the last username attempted into HttpSession for views
		
		// 允许子类设置详细属性
        setDetails(request, authRequest);

        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
		return this.getAuthenticationManager().authenticate(authRequest);
	}
	
	protected void checkValidateCode(HttpServletRequest request) { 
		HttpSession session = request.getSession();
		
	    String sessionValidateCode = obtainSessionValidateCode(session); 
	    //让上一次的验证码失效
	    session.setAttribute(VALIDATE_CODE, null);
	    String validateCodeParameter = obtainValidateCodeParameter(request);  
	    if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {  
	        throw new AuthenticationServiceException("validateCode.notEquals");  
	    }  
	}
	
	private String obtainValidateCodeParameter(HttpServletRequest request) {
		Object obj = request.getParameter(VALIDATE_CODE);
		return null == obj ? "" : obj.toString();
	}

	protected String obtainSessionValidateCode(HttpSession session) {
		Object obj = session.getAttribute(VALIDATE_CODE);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainUsername(HttpServletRequest request) {
		Object obj = request.getParameter(USERNAME);
		return null == obj ? "" : obj.toString();
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		Object obj = request.getParameter(PASSWORD);
		return null == obj ? "" : obj.toString();
	}
	
	
}
